﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;

namespace JiaBao.WPF.Framework.Controls
{

    /// <summary>
    /// DataGrid 优化
    /// </summary>
    public class DataGridEx : DataGrid
    {

        /// <summary>
        /// 编辑换行完成事件
        /// </summary>
        public event EventHandler<DataGridRowEditEndingEventArgs> RowEditEnd;

        /// <summary>
        /// 单元格编辑完成
        /// </summary>
        public event EventHandler<DataGridCellEditEndingEventArgs> CellEditEnd;

        public DataGridEx()
        {  
         
            //重写一些事件

            RowEditEnding += (object sender, DataGridRowEditEndingEventArgs e) =>
            {
                if (e.EditAction == DataGridEditAction.Cancel)
                    return;

                this.LayoutUpdated += LayoutUpdated;

                void LayoutUpdated(object sender1, EventArgs e1)
                {
                    RowEditEnd?.Invoke(sender, e);
                    this.LayoutUpdated -= LayoutUpdated;
                }
            };
             
            CellEditEnding += (object sender, DataGridCellEditEndingEventArgs e) =>
            {
                if (e.EditAction == DataGridEditAction.Cancel)
                    return;

                var newValue = (e.EditingElement as TextBox).Text;
                this.LayoutUpdated += LayoutUpdated;

                void LayoutUpdated(object sender1, EventArgs e1)

                {

                    CellEditEnd?.Invoke(sender, e);
                    this.LayoutUpdated -= LayoutUpdated;
                }
            };
        }

        /// <summary>
        /// 根据名称查找列
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public DataGridColumn Column(string c)
        {
            for (int i = 0; i < Columns.Count; i++)
            {
                if (Columns[i].Header.ToString().ToLower () == c.ToLower ())
                    return Columns[i];
            }
            return null ;
        }

        /// <summary>
        /// 生成行号
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadingRow(DataGridRowEventArgs e)
        {
            base.OnLoadingRow(e);
            if (!e.Row.IsNewItem)
                e.Row.Header = e.Row.GetIndex() + 1;
            else
                e.Row.Header = "*";

        }

      
    }
}
